<template>
  <div class="draw-management">
    <div class="header">
      <h2>比赛抽签管理</h2>
      <div class="match-info" v-if="matchInfo">
        <p>比赛时间：{{ formatDate(matchInfo.match_date) }} {{ formatTime(matchInfo.match_time) }}</p>
        <p>比赛地点：{{ matchInfo.venue_name }}</p>
        <p>对阵双方：{{ matchInfo.home_school_name || '未知主场' }} vs {{ matchInfo.away_school_name || '未知客场' }}</p>
        <p>比赛组别：{{ groupInfo?.home_group?.grade_level_name || '' }} ({{ groupInfo?.home_group?.code || '' }} vs {{ groupInfo?.away_group?.code || '' }})</p>
      </div>
    </div>
    <div class="seating-arrangement">
      <h3>座位安排图 (抽签号即为座位号)</h3>
      <div class="seats">
        <div class="row">
          <div 
            v-for="n in 5" 
            :key="'seat-'+n" 
            class="seat"
            :class="{ 
              empty: !getPlayersInSeat(n).length,
              filled: getPlayersInSeat(n).length > 0
            }"
          >
            <div class="seat-number">{{ n }}</div>
            <div class="seat-players">
              <div 
                v-for="player in getPlayersInSeat(n)" 
                :key="player.id"
                class="player-tag"
                :class="getPlayerSchoolClass(player)"
              >
                {{ player.player_name }}
              </div>
            </div>
          </div>
        </div>
        <div class="row">
          <div 
            v-for="n in 5" 
            :key="'seat-'+(n+5)" 
            class="seat"
            :class="{ 
              empty: !getPlayersInSeat(n+5).length,
              filled: getPlayersInSeat(n+5).length > 0
            }"
          >
            <div class="seat-number">{{ n+5 }}</div>
            <div class="seat-players">
              <div 
                v-for="player in getPlayersInSeat(n+5)" 
                :key="player.id"
                class="player-tag"
                :class="getPlayerSchoolClass(player)"
              >
                {{ player.player_name }}
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="content">
      <div class="left-panel">
        <h3>选手列表</h3>
        <el-tabs type="border-card">
          <el-tab-pane :label="matchInfo?.home_school_name || '主场'">
            <div class="player-list">
              <el-table :data="homePlayers" style="width: 100%" v-loading="loading">
                <el-table-column prop="name" label="姓名"></el-table-column>
                <el-table-column prop="grade_level" label="年级"></el-table-column>
                <el-table-column label="操作" width="160">
                  <template #default="{ row }">
                    <div v-if="isPlayerSelected(row.id)">
                      <el-tag type="success">
                        已抽签：{{ getPlayerDrawNumber(row.id) }}号
                      </el-tag>
                    </div>
                    <div v-else>
                      <el-input-number 
                        v-model="homeDrawNumberInput[row.id]" 
                        :min="1" 
                        :max="10"
                        size="small"
                        placeholder="抽签号"
                        style="width: 90px"
                      ></el-input-number>
                      <el-button 
                        type="primary" 
                        size="small" 
                        @click="saveDrawNumber(row, 'home')"
                        :disabled="!homeDrawNumberInput[row.id]"
                        style="margin-left: 5px"
                      >
                        保存
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
          <el-tab-pane :label="matchInfo?.away_school_name || '客场'">
            <div class="player-list">
              <el-table :data="awayPlayers" style="width: 100%" v-loading="loading">
                <el-table-column prop="name" label="姓名"></el-table-column>
                <el-table-column prop="grade_level" label="年级"></el-table-column>
                <el-table-column label="操作" width="160">
                  <template #default="{ row }">
                    <div v-if="isPlayerSelected(row.id)">
                      <el-tag type="success">
                        已抽签：{{ getPlayerDrawNumber(row.id) }}号
                      </el-tag>
                    </div>
                    <div v-else>
                      <el-input-number 
                        v-model="awayDrawNumberInput[row.id]" 
                        :min="1" 
                        :max="10"
                        size="small"
                        placeholder="抽签号"
                        style="width: 90px"
                      ></el-input-number>
                      <el-button 
                        type="primary" 
                        size="small" 
                        @click="saveDrawNumber(row, 'away')"
                        :disabled="!awayDrawNumberInput[row.id]"
                        style="margin-left: 5px"
                      >
                        保存
                      </el-button>
                    </div>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="right-panel">
        <h3>抽签结果</h3>
        <div class="draw-results">
          <el-table :data="drawResults" style="width: 100%">
            <el-table-column prop="player_name" label="姓名"></el-table-column>
            <el-table-column prop="school_name" label="学校"></el-table-column>
            <el-table-column prop="grade_level" label="年级"></el-table-column>
            <el-table-column prop="draw_number" label="抽签号/座位号" width="120"></el-table-column>
            <el-table-column label="操作" width="100">
              <template #default="{ row }">
                <el-button 
                  type="danger" 
                  size="small" 
                  @click="handleDeleteDraw(row)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 添加确认按钮 -->
    <div class="confirm-section" v-if="drawResults.length > 0">
      <el-button type="primary" @click="confirmDrawResults" :disabled="!isAllTablesDrawn">
        确认抽签结果
      </el-button>
      <div class="hint-text" v-if="!isAllTablesDrawn">
        请完成所有桌子的抽签后再确认（当前：{{ completedTables }}/10）
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

// 配置axios基础URL
axios.defaults.baseURL = 'http://localhost:3000'

const route = useRoute()
const router = useRouter()
const matchId = route.params.id

const loading = ref(false)
const matchInfo = ref(null)
const groupInfo = ref(null)
const homePlayers = ref([])
const awayPlayers = ref([])
const drawResults = ref([])
const homeDrawNumberInput = reactive({})
const awayDrawNumberInput = reactive({})

// 获取比赛信息
const fetchMatchInfo = async () => {
  try {
    console.log('开始获取比赛信息，比赛ID:', matchId)
    const response = await axios.get(`/api/matches/${matchId}`)
    console.log('获取到的比赛信息:', response.data)
    
    if (!response.data) {
      ElMessage.error('获取比赛信息失败：数据为空')
      return
    }
    
    if (!response.data.home_school_id || !response.data.away_school_id) {
      ElMessage.error('获取比赛信息不完整，缺少必要的学校信息')
      console.error('比赛信息不完整:', response.data)
    }
    
    matchInfo.value = response.data
  } catch (error) {
    console.error('获取比赛信息失败:', error.response?.data || error)
    // 显示更具体的错误信息
    if (error.response?.data?.error) {
      ElMessage.error(`获取比赛信息失败: ${error.response.data.error}`)
    } else {
      ElMessage.error('获取比赛信息失败，可能是服务器错误')
    }
  }
}

// 获取可选择的选手
const fetchAvailablePlayers = async () => {
  try {
    const response = await axios.get(`/api/matches/${matchId}/available-players`)
    
    // 更新组别信息
    groupInfo.value = response.data.group
    
    // 正确获取主场和客场选手数据
    homePlayers.value = response.data.players?.home_players || []
    awayPlayers.value = response.data.players?.away_players || []
  } catch (error) {
    console.error('获取选手列表失败:', error.response?.data || error)
    // 显示更具体的错误信息
    if (error.response?.data?.error) {
      ElMessage.error(`获取选手列表失败: ${error.response.data.error}`)
    } else {
      ElMessage.error('获取选手列表失败，可能是服务器错误')
    }
  } finally {
    loading.value = false
  }
}

// 获取抽签结果
const fetchDrawResults = async () => {
  try {
    console.log('开始获取抽签结果，比赛ID:', matchId)
    const response = await axios.get(`/api/matches/${matchId}/draw-results`)
    console.log('获取到的抽签结果:', response.data)
    drawResults.value = response.data || []
  } catch (error) {
    console.error('获取抽签结果失败:', error.response?.data || error)
    
    if (error.response?.status === 404) {
      // 如果还没有抽签结果，设置为空数组
      console.log('未找到抽签结果，设置为空数组')
      drawResults.value = []
    } else {
      // 显示更具体的错误信息
      if (error.response?.data?.error) {
        ElMessage.error(`获取抽签结果失败: ${error.response.data.error}`)
      } else {
        ElMessage.error('获取抽签结果失败，可能是服务器错误')
      }
    }
  }
}

// 保存抽签号
const saveDrawNumber = async (player, type) => {
  try {
    const drawNumber = type === 'home' ? homeDrawNumberInput[player.id] : awayDrawNumberInput[player.id]
    
    if (!drawNumber) {
      ElMessage.warning('请输入抽签号')
      return
    }
    
    // 检查抽签号是否已被同校选手使用
    const sameSchoolPlayers = drawResults.value.filter(
      draw => draw.school_id === player.school_id
    )
    
    if (sameSchoolPlayers.some(p => p.draw_number === drawNumber)) {
      ElMessage.warning('该抽签号已被同校选手使用')
      return
    }
    
    const response = await axios.post(`/api/matches/${matchId}/draw-results`, {
      player_id: player.id,
      draw_number: drawNumber
    })
    
    // 如果成功，添加到抽签结果列表
    if (response.data.id) {
      drawResults.value.push(response.data)
      
      // 清空输入
      if (type === 'home') {
        homeDrawNumberInput[player.id] = null
      } else {
        awayDrawNumberInput[player.id] = null
      }
      
      // 刷新可选择的选手列表
      await fetchAvailablePlayers()
      
      ElMessage.success('抽签成功')
    }
  } catch (error) {
    const errorMessage = error.response?.data?.error || '抽签失败'
    ElMessage.error(errorMessage)
    console.error('Error:', error)
  }
}

// 删除抽签结果
const handleDeleteDraw = async (draw) => {
  try {
    await ElMessageBox.confirm('确定要删除该抽签结果吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const response = await axios.delete(`/api/matches/${matchId}/draw-results/${draw.id}`)
    
    if (response.data.message) {
      drawResults.value = drawResults.value.filter(d => d.id !== draw.id)
      
      // 刷新可选择的选手列表
      await fetchAvailablePlayers()
      
      ElMessage.success('删除成功')
    }
  } catch (error) {
    if (error !== 'cancel') {
      const errorMessage = error.response?.data?.error || '删除失败'
      ElMessage.error(errorMessage)
      console.error('Error:', error)
    }
  }
}

// 获取选手学校样式类
const getPlayerSchoolClass = (player) => {
  if (!matchInfo.value || !player || !matchInfo.value.home_school_id || !player.school_id) {
    console.log('无法获取选手学校样式类，数据不完整', { 
      player: player?.id,
      playerSchoolId: player?.school_id, 
      hasMatchInfo: !!matchInfo.value,
      homeSchoolId: matchInfo.value?.home_school_id
    })
    return ''
  }
  
  return player.school_id === matchInfo.value.home_school_id ? 'home-school' : 'away-school'
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  try {
    return new Date(date).toLocaleDateString('zh-CN')
  } catch (e) {
    console.error('格式化日期错误:', e)
    return '-'
  }
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return '-'
  return time.substring(0, 5)
}

// 计算已完成的桌子数量
const completedTables = computed(() => {
  // 如果matchInfo未定义、为null、或缺少学校ID，返回0
  if (!matchInfo.value || !matchInfo.value.home_school_id || !matchInfo.value.away_school_id) {
    return 0
  }
  
  const drawnTables = new Set()
  const homeSchoolDraws = new Set()
  const awaySchoolDraws = new Set()
  
  drawResults.value.forEach(result => {
    if (result.school_id === matchInfo.value.home_school_id) {
      homeSchoolDraws.add(result.draw_number)
    } else if (result.school_id === matchInfo.value.away_school_id) {
      awaySchoolDraws.add(result.draw_number)
    }
    
    if (homeSchoolDraws.has(result.draw_number) && awaySchoolDraws.has(result.draw_number)) {
      drawnTables.add(result.draw_number)
    }
  })
  
  return drawnTables.size
})

// 判断是否所有桌子都已完成抽签
const isAllTablesDrawn = computed(() => completedTables.value === 10)

// 确认抽签结果
const confirmDrawResults = async () => {
  try {
    if (!isAllTablesDrawn.value) {
      ElMessage.warning('请完成所有桌子的抽签后再确认')
      return
    }

    // 检查比赛信息完整性
    if (!matchInfo.value || !matchInfo.value.id) {
      ElMessage.error('比赛信息不完整，无法提交抽签结果')
      return
    }

    await ElMessageBox.confirm('确定要提交抽签结果吗？提交后将不能修改。', '确认提示', {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 确保每个抽签结果都正确
    const formattedDrawResults = drawResults.value.map(result => {
      // 确保所有必要的字段都存在，避免undefined
      return {
        id: result.id,
        player_id: result.player_id,
        match_id: parseInt(matchId),
        draw_number: result.draw_number,
        seat_number: result.seat_number || result.draw_number,
        school_id: result.school_id
      }
    })

    await axios.post(`/api/matches/${matchId}/confirm-draw`, {
      drawResults: formattedDrawResults
    })

    ElMessage.success('抽签结果已确认')
    // 跳转回抽签列表页面
    router.push('/admin/draw')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('确认抽签结果失败:', error)
      ElMessage.error(error.response?.data?.error || '确认抽签结果失败')
    }
  }
}

// 获取座位上的所有选手
const getPlayersInSeat = (seatNumber) => {
  if (!drawResults.value || !Array.isArray(drawResults.value)) {
    return []
  }
  return drawResults.value.filter(draw => draw && draw.seat_number === seatNumber)
}

// 检查选手是否已被选择
const isPlayerSelected = (playerId) => {
  if (!drawResults.value || !Array.isArray(drawResults.value)) {
    return false
  }
  return drawResults.value.some(draw => draw && draw.player_id === playerId)
}

// 获取选手的抽签号
const getPlayerDrawNumber = (playerId) => {
  if (!drawResults.value || !Array.isArray(drawResults.value)) {
    return null
  }
  const draw = drawResults.value.find(draw => draw && draw.player_id === playerId)
  return draw ? draw.draw_number : null
}

onMounted(async () => {
  loading.value = true
  try {
    console.log('组件挂载，开始获取数据，比赛ID:', matchId)
    
    // 1. 先获取比赛信息
    await fetchMatchInfo()
    
    // 2. 确保比赛信息加载成功后再加载其他数据
    if (matchInfo.value && matchInfo.value.id) {
      console.log('比赛信息获取成功，开始获取选手和抽签数据')
      // 并行获取其他数据
      await Promise.all([
        fetchAvailablePlayers(),
        fetchDrawResults()
      ])
    } else {
      console.error('比赛信息获取失败或不完整，无法加载选手和抽签数据')
      ElMessage.error('比赛信息不完整，请检查比赛ID是否正确')
    }
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载页面数据失败，请尝试刷新页面')
  } finally {
    loading.value = false
  }
})
</script>

<style scoped>
.draw-management {
  padding: 20px;
}

.header {
  margin-bottom: 30px;
}

.match-info {
  background-color: #f5f7fa;
  padding: 15px;
  border-radius: 5px;
  margin-top: 15px;
}

.match-info p {
  margin: 5px 0;
}

.content {
  display: flex;
  gap: 20px;
  margin-bottom: 30px;
}

.left-panel,
.right-panel {
  flex: 1;
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

h3 {
  margin-top: 0;
  margin-bottom: 20px;
}

.seating-arrangement {
  background-color: #fff;
  padding: 20px;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.seats {
  display: flex;
  flex-direction: column;
  gap: 20px;
  align-items: center;
}

.row {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  justify-content: center;
}

.seat {
  width: 80px;
  height: 80px;
  border: 2px solid #dcdfe6;
  border-radius: 5px;
  display: flex;
  flex-direction: column;
  position: relative;
  padding: 10px;
}

.seat.empty {
  background-color: #f5f7fa;
}

.seat.filled {
  background-color: #f0f9eb;
  border-color: #67c23a;
}

.seat-number {
  position: absolute;
  top: 5px;
  left: 5px;
  font-weight: bold;
  color: #909399;
}

.seat-players {
  display: flex;
  flex-direction: column;
  gap: 5px;
  margin-top: 20px;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.player-tag {
  padding: 5px;
  border-radius: 4px;
  font-size: 12px;
  text-align: center;
  width: 100%;
}

.home-school {
  background-color: #f0f9eb;
  color: #67c23a;
  border: 1px solid #e1f3d8;
}

.away-school {
  background-color: #f0f7ff;
  color: #409eff;
  border: 1px solid #d9ecff;
}

.confirm-section {
  margin-top: 30px;
  text-align: center;
  padding: 20px;
  background-color: #fff;
  border-radius: 5px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.hint-text {
  margin-top: 10px;
  color: #909399;
  font-size: 14px;
}
</style> 